package semiProject_army.mvc.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import semiProject_army.mvc.action.ActionHandler;
import semiProject_army.mvc.listener.MVCListener;

@WebServlet("*.mvc")
public class MVCController extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doProcess(req, res);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doProcess(req, res);
	}

	// GET 요청과 Post 요청 모두를 처리하는 메소드
	public void doProcess(
			HttpServletRequest req, HttpServletResponse res) 
					throws ServletException, IOException {

		String uri = req.getRequestURI();
		String cmd = uri.substring(uri.lastIndexOf("/"));
		System.out.println(uri + " => " + cmd);

		ActionHandler action = 
				(ActionHandler)MVCListener.getActionMap().get(cmd);

		String viewPage = action.execute(req, res);
		String dispatcher[] = viewPage.split("[|]");

		switch(dispatcher[0]) {
		case "f" : 
			RequestDispatcher rd = 
			req.getRequestDispatcher(dispatcher[1]);
			rd.forward(req, res);
			break;

		case "r" : 
			res.sendRedirect(dispatcher[1]);
			break;
		}


	}

}
